﻿using GetData.webProductClass;
using jutehui.GetData;
using jutehui.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace GetData
{
    public class yifen
    {
        /// <summary>
        /// 超值分享汇 HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL(string url, int navType)
        {
            var htmlText = CustomMethod.GetHtmlByHttpHelper(url);
            var productList = GetProductByRegexToHtml(htmlText, navType);
            if (productList == null || productList.Count < 1)
            {
                return "网络异常，未能获取数据";
            }
            // GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string errorMsg = "";
            dt = CustomMethod.ListToDataTable<Product>(productList, "Product", ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product bll = new jutehui.BLL.Product();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            {
                CustomMethod.WriteLog("一分网：" + msg);
                return msg;
            }
        }
        /// <summary>
        /// 根据正则解析商品信息
        /// </summary>
        /// <param name="htmlText"></param>
        /// <param name="type">海购还是精选</param>
        /// <returns></returns>
        private List<Product> GetProductByRegexToHtml(string htmlText, int type)
        {
            ProductTypeEnum pEnum = new ProductTypeEnum();
            List<Product> pList = new List<Product>();
            string productRegex = @" <li class=""clearfix dp "" id=(.*?)>[\s\S]*?</li>";
            var list = CustomMethod.GetInfoByRegex(productRegex, htmlText, 0);
            if (list == null || list.Count < 1)
            {
                string msg = "一分网：GetProductByRegex ，没有抓到匹配的商品，检查匹配规则。";
                CustomMethod.WriteLog(msg);
                return null;
            }
            //每个商品匹配所有相关属性并赋值
            for (int index = 0; index < list.Count; index++)
            {
                Product product = new Product();
                product.FromWeb = "一分网";
                product.TypeId = type;
                try
                {
                    var herfList = CustomMethod.GetInfoFroma(list[index]);
                    if (herfList == null || herfList.Count < 2)
                    {
                        CustomMethod.WriteLog("一分网：没有获取到herf连接数据");
                        continue;
                    }
                    //-------------------------------------获取商品分类 ----------------------------
                    string detailUrl = herfList[0];
                    string detailText = CustomMethod.GetHtmlByHttpHelper(detailUrl);
                    string regex = @"<div class=""station_nav"">[\s\S]*?</div>";
                    product.ProductTypeId = pEnum.GetProductTypeId(detailText, regex, typeof(ProductTypeEnum.yifenType),0);
                    //----------------------------------
                    product.Pname = herfList[1];
                    product.ImgUrl = "http://www.yifen.com/" + CustomMethod.GetImgUrl(list[index], "一分网");
                    if (product.ImgUrl == "")
                    {
                        CustomMethod.WriteLog("一分网：没有获取到图片链接");
                        continue;
                    }
                    //获取连接和数据源
                    string sourceLinkRegex = @"<span class=""list_info"">[\s\S]*?<div class=""both"">";
                    var souContenList = CustomMethod.GetInfoByRegex(sourceLinkRegex, list[index], 0);
                    if (souContenList == null || souContenList.Count < 1)
                    {
                        CustomMethod.WriteLog("一分网：没有获取到商品链接和来源区域内容");
                        continue;
                    }
                    string url = "";
                    string herfUrl = "";//存储截取下来的url
                    string productUrl = "";
                    int startIndex = 0;
                    if (type == (int)MallsEnumClass.NavigationType.精选)
                    {
                        var sourHerfList = CustomMethod.GetInfoFroma(souContenList[0]);
                        if (sourHerfList == null || sourHerfList.Count < 3)
                        {
                            CustomMethod.WriteLog("一分网：没有获取到商品链接和来源");
                            continue;
                        }
                        product.Source = sourHerfList[1];
                        herfUrl = sourHerfList[2];

                    }
                    else
                    {
                        string sourRegex = @" <span class=""dp_shop"">([^<]+)</span>";
                        var sourContent = CustomMethod.GetInfoByRegex(sourRegex, souContenList[0], 1);
                        if (sourContent == null || sourContent.Count < 1)
                        {
                            CustomMethod.WriteLog("一分网：没有获取到商品来源，海淘");
                            continue;
                        }
                        product.Source = sourContent[0];
                        var link = CustomMethod.GetInfoFroma(souContenList[0]);
                        if (link == null || souContenList.Count < 1)
                        {

                            CustomMethod.WriteLog("一分网：没有获取到商品链接，海淘");
                            continue;
                        }
                        herfUrl = link[0];
                    }
                    startIndex = herfUrl.LastIndexOf("u=");
                    if (startIndex > 0)
                    {
                        url = herfUrl.Substring(startIndex + 2, herfUrl.Length - startIndex - 2);
                    }
                    else
                    {
                        url = herfUrl;
                    }
                    product.Plink = MallsEnumClass.GetSourceUrl(url, ref productUrl);
                    if (product.Plink == "")
                    {
                        if (productUrl == "")
                        {
                            CustomMethod.WriteLog("一分网：没有获取到商品链接");
                        }
                        continue;
                    }
                    //描述
                    string desRegex = @"<div class=""hui-content-text"">[\s\S]*?</div>";
                    var desContent = CustomMethod.GetInfoByRegex(desRegex, list[index], 0);
                    if (desContent == null || desContent.Count < 1)
                    {
                        CustomMethod.WriteLog("一分网：没有获取到商品描述区域");
                        continue;
                    }
                    string despRegex = @"<p>[\s\S]*?</p>";
                    var desList = CustomMethod.GetInfoByRegex(despRegex, desContent[0], 0);
                    string description = "";
                    if (desList == null || desList.Count < 1)
                    {
                        product.Description = product.Pname;
                    }
                    else
                    {
                        for (int count = 0; count < desList.Count; count++)
                        {
                            description += Regex.Replace(desList[count], @"<(.[^>]*)>", "") + "|||";

                        }
                        int endIndex = description.LastIndexOf("遇到问题");
                        if (endIndex > 0)
                        {
                            product.Description = description.Substring(0, endIndex);
                        }
                        else
                        {
                            product.Description = description;
                        }
                    }
                    product.Memo = productUrl;
                    product.UpdateTime = DateTime.Now;
                    product.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    product.Price = "";
                    product.Pname = System.Web.HttpUtility.HtmlEncode(product.Pname);
                    pList.Add(product);
                }
                catch (Exception ex)
                {
                    CustomMethod.WriteLog("一分网：" + ex.Message.ToString());
                    continue;
                }
            }
            var newList = CustomMethod.GetDistinctProdcuts(pList);
            newList.Reverse();
            return newList;
        }
    }
}
